package cn.qh.seasonal.vo;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.lang.model.element.TypeElement;

/**
 * @Description: TODO
 * @author: MengJiaLin
 * @date: 2021年10月25日 11:56
 */
@RestControllerAdvice(value = "cn.qh.seasonal.controller")
public class CommonResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //如果注解在类上就false
        if (returnType.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }
        //如果注解在方法上就false
        return !returnType.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (null == body) {
            return CommonResponse.builder().code(200).message("no").data(null).build();
        } else if (body instanceof CommonResponse) {
            return body;
        } else {
            return CommonResponse.builder().code(200).message("okokok").data(body).build();
        }
    }
}
